const { Server } = require('socket.io');

// 将socket服务器监听3001端口
const io = new Server(3000);
const ROOM = 'my_room';

// 监听客户端连接上的事件
io.on('connection', (socket) => {
    io.on('disconnect',() => {
        console.warn(`【${socket.id}】断开连接`)
    })

    // 首先要让socket加入某一房间
    socket.join(ROOM);
    console.log(`${socket.id} connected room ${ROOM}`);

    // 向某一空间广播，包括自己
    const doBroadCast = (info,all) => {
        if(all){
            io.in(ROOM).emit('leis-common',info)
        }else{
            socket.broadcast.in(ROOM).emit('leis-common',info)
        }
    }

    // 单独发送，直接使用emit
    socket.on('leis-person',data => {
        console.log('leis-person ====> ',data)
        switch (data.type){
            case 'login':{
                // 回应登陆成功
                doBroadCast({message:'',type:'online',id:socket.id})
                socket.emit('leis-client-person',{status:200,type:'login',id:socket.id})
                break
            }
            case 'msg-common':{
                doBroadCast({message:data.message,type:'msg-common',id:socket.id},true)
                break
            }
        }
    })

});

